<?php

namespace App\Models\Posts;

use App\Models\Circle\WxCircle;
use App\Models\User\WxUser;
use App\Models\User\WxUserFollow;
use App\Models\WxChat;
use App\Wen\Utils\Settings;
use App\Wen\Utils\Utils;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
use Laravel\Scout\Searchable;

class WxPost extends Model
{
    use HasDateTimeFormatter;
    use Searchable;

//    use SoftDeletes;

    protected $table = 'wx_posts';

    protected $appends = [];

    protected $fillable = ['posts_title','posts_content', 'user_id', 'pay_content_id', 'circle_id', 'circle_name', 'address_id', 'tags_id', 'files_id', 'sounds_id', 'video_id', 'goods_id','vote_id', 'voter_id', 'has_fields', 'img_count','is_wechat_sph', 'is_anonymous', 'is_only_text', 'is_examine', 'is_blur', 'weight','degree','device', 'last_reply_at','ip', 'longitude', 'latitude', 'country', 'province', 'city', 'district', 'refer_id', 'tenant_id', 'tenant_obj', 'update_at', 'create_at'];

    protected static function boot()
    {
        parent::boot();
        static::deleted(function ($model) {
            WxChat::where('expand_type', 101)->where('expand_id', $model->id)->forceDelete();
        });
    }

    public function searchableAs()
    {
        return str_replace('.', '_', str_replace(['https://', 'http://'], '', env('APP_URL', 'minisns.cn'))).'_'.'post_wx_posts_index';
    }
    /**
     * 获取模型的可索引的数据。
     *
     * @return array
     */
    public function toSearchableArray()
    {
        $array = $this->toArray();

        $tags_ids = [];
        WxPostsTag::where('posts_id', $array['id'])->get(['tags_id'])->map(function ($v) use (&$tags_ids){
            if($v){
                $tags_ids[] = $v->tags_id;
            }
        });
        $tags_name = [];
        if($tags_ids){
            WxTag::whereIn('id', $tags_ids)->get(['tags_name'])->map(function ($v) use (&$tags_name){
                $tags_name[] = $v->tags_name;
            });
        }

        $search_data = [
            'id' => $array['id'],
            'posts_content' => _mini_phone(_mini_aite_replace(_mini_emoji($array['posts_content'], true)), true),
            'circle_name' => $array['circle_name'],
            'address_name' => $array['address_id'] ? WxPostsAddress::where('id', $array['address_id'])->value('address_name') : '',
            'user_name' => WxUser::where('id', $array['user_id'])->value('user_name'),
            'tags_name' => implode(',', $tags_name),
            'is_examine' => $array['is_examine'],
            'posts_state' => $array['posts_state'],
            'tenant_id' => $array['tenant_id']
        ];

        return $search_data;
    }
    /**
     * 确定模型是否可搜索
     *
     * @return bool
     */
    public function shouldBeSearchable()
    {
        return $this->posts_state == 0;
    }

    /**  被重载的数据保存在此  */
    private $data = array();

    function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
    }


    public function circle()
    {
        return $this->belongsTo(WxCircle::class, 'circle_id', 'id');
    }

    public function comment()
    {
        return $this->hasMany(WxComment::class, 'posts_id', 'id');
    }

    public function user()
    {
        return $this->hasOne(WxUser::class, 'id', 'user_id');
    }

    public function images()
    {
        return $this->hasMany(WxPostsImg::class, 'posts_id', 'id');
    }

    public function address()
    {
        return $this->hasOne(WxPostsAddress::class, 'id', 'address_id');
    }


    public function video()
    {
        return $this->hasOne(WxPostsVideo::class, 'posts_id', 'id');
    }

    // 远程关联
    public function tags()
    {
        return $this->hasManyThrough(
            WxTag::class,
            WxPostsTag::class,
            'posts_id',
            'id',
            'id',
            'id'
        );
    }

    public function like()
    {
        return $this->hasMany(WxLike::class, 'posts_id', 'id');
    }


    public function userFollow()
    {
        return $this->hasMany(WxUserFollow::class, 'user_follow_id', 'user_id');
    }

    /**
     * 文章内容获取器
     *
     * @param string $value
     * @return string
     */
    public function getPostsContentAttribute($value)
    {
        return str_replace("\n", "<br>", $value);
    }

    /**
     * 判断是否是我自己的笔记
     *
     * @return string
     */
    public static function isMyPosts($uid, $posts_id)
    {
        $postsUserId = WxPost::where('id', $posts_id)->pluck('user_id')->first();
        if ($uid == $postsUserId) {
            return true;
        } else {
            return false;
        }
    }



    /**
     * 获取器判断是否关注该用户
     *
     * @return string
     */
    public static function isFollowUser($uid, $user_follow_id)
    {
        return (boolean)(Cache::remember($uid.':follow:user:'.$user_follow_id, 36000, function () use ($uid, $user_follow_id){
            $exists = WxUserFollow::where('user_id', $uid)->where('user_follow_id', $user_follow_id)->exists();
            return $exists;
        }));
    }

    /**
     * 获取器判断用户是否喜欢
     *
     * @return string
     */
    public static function isLike($uid, $posts_id)
    {
        return (boolean)(Cache::remember($uid.':like:post:'.$posts_id, 36000, function () use ($uid, $posts_id){
            $exists = WxLike::where('user_id', $uid)->where('posts_id', $posts_id)->exists();
            return $exists;
        }));
    }


    /**
     * 获取器判断是否收藏
     *
     * @return string
     */
    public static function isCollec($uid, $posts_id)
    {
        return (boolean)(Cache::remember($uid.':collect:post:'.$posts_id, 36000, function () use ($uid, $posts_id){
            $exists = WxCollect::where('user_id', $uid)->where('posts_id', $posts_id)->exists();
            return $exists;
        }));
    }

    public function getFormatTimeAttribute()
    {
        return format_datetime($this->created_at);
    }

    // 判断文章是否超出
    public function getIsContentBeyondAttribute()
    {
        $textCount = mb_strlen(strip_tags($this->posts_content));
        $isBr = substr_count($this->posts_content, '<br>');
        if ($isBr >= 3 || $textCount >= 70) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取一张图片
     * @return mixed
     */
    public function getMainImageAttribute()
    {
        $postsVideo = WxPostsVideo::where('posts_id', $this->id)->first(['video_thumb_url']);
        if($postsVideo && !_empty_($postsVideo['video_thumb_url'])){
            return $postsVideo['video_thumb_url'];
        }else{
            $postsImg = WxPostsImg::where('posts_id', $this->id)->first(['img_url']);
            return $postsImg ? $postsImg['img_url'] : '';
        }
    }

    /**
     * 获取一张图片
     * @return mixed
     */
    public function getImageaAttribute()
    {
        $data = [];

        $postsVideo = WxPostsVideo::where('posts_id', $this->id)->first(['video_thumb_url']);
        if($postsVideo && !_empty_($postsVideo['video_thumb_url'])){
            $data['img_url'] =  Utils::imgWithStyle($postsVideo['video_thumb_url'], 0);
        }else{
            $postsImg = WxPostsImg::where('posts_id', $this->id)->first(['img_url']);
            $data['img_url'] = $postsImg ? Utils::imgWithStyle($postsImg['img_url'], 0) : '';
        }
        return $data;
    }

    /**
     * 前端用
     */
    public function getIsEllipsisAttribute()
    {
        return false;
    }


    /**
     * 获取图片组
     */
    public function getImagesUrlAttribute()
    {
        return WxPostsImg::where('posts_id', $this->id)->get()->map(function ($v) {
            return $v['img_url'];
        });
    }

    public function getWeightAttribute($value){
        return strtotime($value);
    }

    public function getIsStickyAttribute($value){
        return (bool)$value;
    }

    public function getIsBlurAttribute($value){
        return (bool)$value;
    }

    public function getIsRewardAttribute($value){
        return (bool)$value;
    }

    public function getUsedsAttribute($value){
        if($value){
            return explode(',', $value);
        }
        return [];
    }


    public function getBureausAttribute($value){
        if($value){
            return explode(',', $value);
        }
        return [];
    }



    public function getDeviceAttribute($v)
    {
        if($v){
            return ['app'=>'App', 'h5'=>'网页端', 'mp'=>'小程序', 'pc'=>'PC端'][$v];
        }else{
            return '';
        }
    }

    /**
     * 获取评论
     */
    public function getComment($posts_id, $field = ["*"])
    {
        return WxComment::where('comment_state', 1)->where('posts_id', $posts_id)->limit(2)->orderBy('id', 'desc')->get($field);
    }

    /**
     * 获取评论数量
     */
    public function getCommentCount($posts_id)
    {

        return WxComment::where('comment_state', 1)->where('posts_id', $posts_id)->count();
    }

    public function getIpAddressAttribute()
    {
        if($this->country) {
            $show = Settings::get('app_ip_post_show', 3);
            if ($show == 0) {
                return '';
            } else if ($show == 1) {
                return ' '.$this->country;
            } else if ($show == 2) {
                return ' '.$this->province;
            } else if ($show == 3) {
                return ' '.$this->city;
            } else if ($show == 4) {
                return ' '.$this->district;
            }
        }
        return '';
    }

}
